<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>读者写者问题模拟</title>
  <style>
    :root {
      --reader-color: #4e73df;
      --writer-color: #e74a3b;
      --active-color: #1cc88a;
      --waiting-color: #f6c23e;
      --history-color: #6c757d;
      --bg-color: #f8f9fc;
      --card-bg: #ffffff;
      --text-color: #5a5c69;
      --shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
      --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    }

    body {
      font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      max-width: 1200px;
      margin: 0 auto;
      padding: 2rem;
      background-color: var(--bg-color);
      color: var(--text-color);
      line-height: 1.6;
    }

    h1, h2, h3 {
      margin: 0;
      font-weight: 600;
    }

    .dashboard {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 2rem;
      margin-bottom: 2rem;
    }

    .card {
      background: var(--card-bg);
      border-radius: 0.5rem;
      padding: 1.5rem;
      box-shadow: var(--shadow);
      transition: var(--transition);
      border: none;
      position: relative;
      overflow: hidden;
    }

    .card::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 0.5rem;
      background: linear-gradient(90deg, var(--reader-color), var(--writer-color));
    }

    .card:hover {
      transform: translateY(-5px);
      box-shadow: 0 0.5rem 1.5rem rgba(0, 0, 0, 0.2);
    }

    .card-header {
      display: flex;
      align-items: center;
      gap: 1rem;
      margin-bottom: 1.5rem;
      padding-bottom: 1rem;
      border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }

    .card-icon {
      width: 3rem;
      height: 3rem;
      border-radius: 50%;
      display: grid;
      place-items: center;
      font-size: 1.5rem;
      box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }

    .reader-icon {
      background: linear-gradient(135deg, rgba(78, 115, 223, 0.2), rgba(78, 115, 223, 0.1));
      color: var(--reader-color);
    }

    .writer-icon {
      background: linear-gradient(135deg, rgba(231, 74, 59, 0.2), rgba(231, 74, 59, 0.1));
      color: var(--writer-color);
    }

    .history-icon {
      background: linear-gradient(135deg, rgba(108, 117, 125, 0.2), rgba(108, 117, 125, 0.1));
      color: var(--history-color);
    }

    .status-indicator {
      font-size: 1.25rem;
      font-weight: 500;
      padding: 1rem;
      border-radius: 0.5rem;
      text-align: center;
      margin-bottom: 1.5rem;
      transition: var(--transition);
      position: relative;
      overflow: hidden;
    }

    .status-indicator::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0.1;
      z-index: 0;
    }

    .active {
      color: var(--active-color);
    }
    .active::after {
      background-color: var(--active-color);
    }

    .waiting {
      color: var(--waiting-color);
    }
    .waiting::after {
      background-color: var(--waiting-color);
    }

    .controls {
      display: flex;
      gap: 1rem;
      justify-content: center;
      flex-wrap: wrap;
      margin-bottom: 2rem;
    }

    .control-group {
      display: flex;
      gap: 1rem;
      align-items: center;
      background: var(--card-bg);
      padding: 1rem;
      border-radius: 0.5rem;
      box-shadow: var(--shadow);
    }

    button {
      padding: 0.75rem 1.5rem;
      border: none;
      border-radius: 0.35rem;
      display: flex;
      align-items: center;
      gap: 0.5rem;
      font-weight: 600;
      cursor: pointer;
      transition: var(--transition);
      box-shadow: 0 0.15rem 0.5rem rgba(0, 0, 0, 0.1);
      position: relative;
      overflow: hidden;
    }

    button::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
      opacity: 0;
      transition: var(--transition);
    }

    button:hover {
      transform: translateY(-2px);
      box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }

    button:hover::after {
      opacity: 1;
    }

    button:active {
      transform: translateY(0);
    }

    .add-reader {
      background: linear-gradient(135deg, var(--reader-color), #3a5ccc);
      color: white;
    }

    .add-writer {
      background: linear-gradient(135deg, var(--writer-color), #c0392b);
      color: white;
    }

    .toggle-history {
      background: linear-gradient(135deg, var(--history-color), #5a6268);
      color: white;
    }

    .process-list {
      display: grid;
      gap: 1rem;
      margin-top: 1.5rem;
      max-height: 300px;
      overflow-y: auto;
      padding-right: 0.5rem;
    }

    /* 自定义滚动条 */
    .process-list::-webkit-scrollbar {
      width: 6px;
    }

    .process-list::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 3px;
    }

    .process-list::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 3px;
    }

    .process-list::-webkit-scrollbar-thumb:hover {
      background: rgba(0, 0, 0, 0.3);
    }

    .process-item {
      padding: 1rem;
      border-radius: 0.35rem;
      background: var(--card-bg);
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-shadow: 0 0.15rem 0.5rem rgba(0, 0, 0, 0.05);
      transition: var(--transition);
      border: 1px solid rgba(0, 0, 0, 0.05);
      position: relative;
    }

    .process-item:hover {
      transform: translateX(5px);
      box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
    }

    .reader-process {
      border-left: 4px solid var(--reader-color);
    }

    .writer-process {
      border-left: 4px solid var(--writer-color);
    }

    .badge {
      padding: 0.25rem 0.75rem;
      border-radius: 1rem;
      font-size: 0.75rem;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }

    .active-badge {
      background: linear-gradient(135deg, var(--active-color), #17a673);
      color: white;
    }

    .waiting-badge {
      background: linear-gradient(135deg, var(--waiting-color), #e6a704);
      color: white;
    }

    .remove-btn {
      background: rgba(231, 74, 59, 0.1);
      color: var(--writer-color);
      border: none;
      padding: 0.5rem;
      border-radius: 50%;
      cursor: pointer;
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: var(--transition);
      margin-left: 0.5rem;
    }

    .remove-btn:hover {
      background: rgba(231, 74, 59, 0.2);
      transform: rotate(90deg);
    }

    .process-info {
      display: flex;
      align-items: center;
      gap: 0.75rem;
    }

    .process-icon {
      font-size: 1.1rem;
    }

    .reader-icon-sm {
      color: var(--reader-color);
    }

    .writer-icon-sm {
      color: var(--writer-color);
    }

    .stats {
      display: flex;
      justify-content: space-between;
      margin-top: 2rem;
      padding-top: 1rem;
      border-top: 1px solid rgba(0, 0, 0, 0.05);
      font-size: 0.9rem;
      color: rgba(0, 0, 0, 0.6);
      font-weight: 600;
    }

    .title-container {
      text-align: center;
      margin-bottom: 3rem;
    }

    .title-container h1 {
      font-size: 2.5rem;
      margin-bottom: 0.5rem;
      background: linear-gradient(90deg, var(--reader-color), var(--writer-color));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      display: inline-block;
      position: relative;
      padding-bottom: 1rem;
    }

    .title-container h1::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 100px;
      height: 4px;
      background: linear-gradient(90deg, var(--reader-color), var(--writer-color));
      border-radius: 2px;
    }

    .title-container p {
      color: rgba(0, 0, 0, 0.6);
      max-width: 600px;
      margin: 0 auto;
      font-size: 1.1rem;
    }

    /* 历史记录面板 */
    .history-panel {
      position: fixed;
      top: 0;
      right: -400px;
      width: 380px;
      height: 100vh;
      background: var(--card-bg);
      box-shadow: -5px 0 15px rgba(0, 0, 0, 0.1);
      transition: var(--transition);
      z-index: 1000;
      padding: 1.5rem;
      overflow-y: auto;
    }

    .history-panel.active {
      right: 0;
    }

    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1.5rem;
      padding-bottom: 1rem;
      border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }

    .close-history {
      background: none;
      border: none;
      font-size: 1.5rem;
      cursor: pointer;
      color: var(--text-color);
      padding: 0.5rem;
    }

    .history-list {
      display: grid;
      gap: 0.75rem;
    }

    .history-item {
      padding: 0.75rem;
      border-radius: 0.35rem;
      background: rgba(0, 0, 0, 0.02);
      font-size: 0.9rem;
      border-left: 3px solid var(--history-color);
    }

    .history-item.reader {
      border-left-color: var(--reader-color);
    }

    .history-item.writer {
      border-left-color: var(--writer-color);
    }

    .history-time {
      color: rgba(0, 0, 0, 0.5);
      font-size: 0.8rem;
      margin-top: 0.25rem;
    }

    /* 遮罩层 */
    .overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 999;
      opacity: 0;
      pointer-events: none;
      transition: var(--transition);
    }

    .overlay.active {
      opacity: 1;
      pointer-events: auto;
    }

    /* 速度控制 */
    .speed-control {
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }

    .speed-label {
      font-weight: 600;
      color: var(--text-color);
    }

    .speed-slider {
      -webkit-appearance: none;
      width: 120px;
      height: 6px;
      border-radius: 3px;
      background: #ddd;
      outline: none;
    }

    .speed-slider::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: var(--reader-color);
      cursor: pointer;
      transition: var(--transition);
    }

    .speed-slider::-webkit-slider-thumb:hover {
      transform: scale(1.2);
    }

    .speed-value {
      min-width: 40px;
      text-align: center;
      font-weight: 600;
    }

    @media (max-width: 768px) {
      body {
        padding: 1rem;
      }

      .dashboard {
        grid-template-columns: 1fr;
      }

      .title-container h1 {
        font-size: 2rem;
      }

      .controls {
        flex-direction: column;
      }

      .control-group {
        width: 100%;
        justify-content: space-between;
      }

      .history-panel {
        width: 85%;
        right: -85%;
      }
    }
  </style>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div class="title-container">
  <h1>
    <i class="fas fa-book-reader" style="color: var(--reader-color);"></i>
    读者写者问题模拟系统
    <i class="fas fa-user-edit" style="color: var(--writer-color);"></i>
  </h1>

</div>

<div class="controls">
  <div class="control-group">
    <button class="add-reader" id="addReaderBtn">
      <i class="fas fa-plus"></i> 添加读者
    </button>
    <button class="add-writer" id="addWriterBtn">
      <i class="fas fa-plus"></i> 添加写者
    </button>
  </div>

  <div class="control-group">
    <div class="speed-control">
      <span class="speed-label">速度:</span>
      <input type="range" min="1" max="10" value="5" class="speed-slider" id="speedSlider">
      <span class="speed-value" id="speedValue">5x</span>
    </div>
    <button class="toggle-history" id="toggleHistoryBtn">
      <i class="fas fa-history"></i> 历史记录
    </button>
  </div>
</div>

<div class="dashboard">
  <div class="card">
    <div class="card-header">
      <div class="card-icon reader-icon">
        <i class="fas fa-users"></i>
      </div>
      <h2>读者状态</h2>
    </div>
    <div class="status-indicator" id="readerStatus">空闲中</div>
    <div class="process-list" id="readersList"></div>
    <div class="stats">
      <span>总读者: <span id="totalReaders">0</span></span>
      <span>活跃读者: <span id="activeReadersCount">0</span></span>
    </div>
  </div>

  <div class="card">
    <div class="card-header">
      <div class="card-icon writer-icon">
        <i class="fas fa-user-edit"></i>
      </div>
      <h2>写者状态</h2>
    </div>
    <div class="status-indicator" id="writerStatus">空闲中</div>
    <div class="process-list" id="writersList"></div>
    <div class="stats">
      <span>总写者: <span id="totalWriters">0</span></span>
      <span>活跃写者: <span id="activeWritersCount">0</span></span>
    </div>
  </div>
</div>

<!-- 历史记录面板 -->
<div class="overlay" id="overlay"></div>
<div class="history-panel" id="historyPanel">
  <div class="card-header history-header">
    <h2><i class="fas fa-history"></i> 操作历史</h2>
    <button class="close-history" id="closeHistoryBtn">
      <i class="fas fa-times"></i>
    </button>
  </div>
  <div class="history-list" id="historyList"></div>
</div>

<script>
  // 共享资源状态
  let activeReaders = 0;
  let isWriting = false;
  let readers = [];
  let writers = [];
  let nextId = 1;
  let speedFactor = 5; // 默认速度因子
  let historyLog = [];

  // 信号量实现
  const semaphore = (initial = 1) => ({
    value: initial,
    queue: [],
    async acquire() {
      return new Promise(resolve => {
        if (this.value > 0) {
          this.value--;
          resolve();
        } else {
          this.queue.push(resolve);
        }
      });
    },
    release() {
      if (this.queue.length > 0) {
        const next = this.queue.shift();
        next();
      } else {
        this.value++;
      }
    }
  });

  const readCountMutex = semaphore(); // 保护activeReaders计数
  const resourceMutex = semaphore();  // 读写互斥

  // 添加历史记录
  function addHistory(type, action, processId) {
    const now = new Date();
    const timeString = now.toLocaleTimeString();
    const entry = {
      type,
      action,
      processId,
      time: timeString,
      timestamp: now
    };

    historyLog.push(entry);
    updateHistoryUI(entry);

    // 保持历史记录不超过20条
    if (historyLog.length > 20) {
      historyLog.shift();
      const historyList = document.getElementById('historyList');
      if (historyList.firstChild) {
        historyList.removeChild(historyList.firstChild);
      }
    }
  }

  // 更新历史记录UI
  function updateHistoryUI(entry) {
    const historyList = document.getElementById('historyList');
    const item = document.createElement('div');
    item.className = `history-item ${entry.type}`;

    let actionText = '';
    switch(entry.action) {
      case 'add':
        actionText = `添加${entry.type === 'reader' ? '读者' : '写者'} #${entry.processId}`;
        break;
      case 'remove':
        actionText = `移除${entry.type === 'reader' ? '读者' : '写者'} #${entry.processId}`;
        break;
      case 'start':
        actionText = `${entry.type === 'reader' ? '读者' : '写者'} #${entry.processId} 开始${entry.type === 'reader' ? '读取' : '写入'}`;
        break;
      case 'end':
        actionText = `${entry.type === 'reader' ? '读者' : '写者'} #${entry.processId} 结束${entry.type === 'reader' ? '读取' : '写入'}`;
        break;
    }

    item.innerHTML = `
      <div>${actionText}</div>
      <div class="history-time">${entry.time}</div>
    `;

    historyList.appendChild(item);
    historyList.scrollTop = historyList.scrollHeight;
  }

  // 计算延迟时间（考虑速度因子）
  function getDelayTime(baseTime) {
    return baseTime / speedFactor;
  }

  // 更新界面状态
  function updateUI() {
    // 更新读者状态
    const readerStatus = document.getElementById('readerStatus');
    if (activeReaders > 0) {
      readerStatus.textContent = `${activeReaders} 位读者正在读取`;
      readerStatus.className = 'status-indicator active';
    } else {
      readerStatus.textContent = '空闲中';
      readerStatus.className = 'status-indicator';
    }

    // 更新写者状态
    const writerStatus = document.getElementById('writerStatus');
    if (isWriting) {
      writerStatus.textContent = '正在写入';
      writerStatus.className = 'status-indicator active';
    } else {
      writerStatus.textContent = '空闲中';
      writerStatus.className = 'status-indicator';
    }

    // 更新统计信息
    document.getElementById('totalReaders').textContent = readers.length;
    document.getElementById('activeReadersCount').textContent = readers.filter(r => r.active).length;
    document.getElementById('totalWriters').textContent = writers.length;
    document.getElementById('activeWritersCount').textContent = writers.filter(w => w.active).length;

    // 更新进程列表
    updateProcessLists();
  }

  // 更新进程列表
  function updateProcessLists() {
    const readersList = document.getElementById('readersList');
    const writersList = document.getElementById('writersList');

    readersList.innerHTML = readers.map(reader => `
        <div class="process-item reader-process">
          <div class="process-info">
            <i class="fas fa-user process-icon reader-icon-sm"></i>
            <span>读者 #${reader.id}</span>
          </div>
          <div>
            ${reader.active
            ? '<span class="badge active-badge">活动中</span>'
            : '<span class="badge waiting-badge">等待中</span>'}
            <button class="remove-btn" data-id="${reader.id}" data-type="reader" title="移除读者">
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>
      `).join('');

    writersList.innerHTML = writers.map(writer => `
        <div class="process-item writer-process">
          <div class="process-info">
            <i class="fas fa-user-edit process-icon writer-icon-sm"></i>
            <span>写者 #${writer.id}</span>
          </div>
          <div>
            ${writer.active
            ? '<span class="badge active-badge">活动中</span>'
            : '<span class="badge waiting-badge">等待中</span>'}
            <button class="remove-btn" data-id="${writer.id}" data-type="writer" title="移除写者">
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>
      `).join('');

    // 绑定移除事件
    document.querySelectorAll('.remove-btn').forEach(btn => {
      btn.addEventListener('click', function() {
        const id = parseInt(this.dataset.id);
        const type = this.dataset.type;
        removeProcess(id, type);
      });
    });
  }

  // 读者行为
  async function createReader() {
    const reader = { id: nextId++, active: false };
    readers.push(reader);
    addHistory('reader', 'add', reader.id);
    updateUI();

    while (readers.includes(reader)) {
      await readCountMutex.acquire();

      if (activeReaders === 0) {
        await resourceMutex.acquire(); // 第一个读者获取资源锁
      }

      activeReaders++;
      reader.active = true;
      addHistory('reader', 'start', reader.id);
      updateUI();
      readCountMutex.release();

      // 模拟读取操作
      await new Promise(resolve =>
              setTimeout(resolve, getDelayTime(Math.random() * 3000 + 2000)));

      await readCountMutex.acquire();
      activeReaders--;
      reader.active = false;
      addHistory('reader', 'end', reader.id);

      if (activeReaders === 0) {
        resourceMutex.release(); // 最后一个读者释放资源锁
      }

      updateUI();
      readCountMutex.release();

      // 等待一段时间再尝试读取
      await new Promise(resolve =>
              setTimeout(resolve, getDelayTime(Math.random() * 4000 + 2000)));
    }
  }

  // 写者行为
  async function createWriter() {
    const writer = { id: nextId++, active: false };
    writers.push(writer);
    addHistory('writer', 'add', writer.id);
    updateUI();

    while (writers.includes(writer)) {
      await resourceMutex.acquire(); // 获取资源锁
      isWriting = true;
      writer.active = true;
      addHistory('writer', 'start', writer.id);
      updateUI();

      // 模拟写入操作
      await new Promise(resolve =>
              setTimeout(resolve, getDelayTime(Math.random() * 4000 + 1000)));

      isWriting = false;
      writer.active = false;
      addHistory('writer', 'end', writer.id);
      resourceMutex.release(); // 释放资源锁
      updateUI();

      // 等待一段时间再尝试写入
      await new Promise(resolve =>
              setTimeout(resolve, getDelayTime(Math.random() * 6000 + 3000)));
    }
  }

  // 移除进程
  function removeProcess(id, type) {
    if (type === 'reader') {
      const index = readers.findIndex(r => r.id === id);
      if (index !== -1) {
        readers.splice(index, 1);
        addHistory('reader', 'remove', id);
      }
    } else {
      const index = writers.findIndex(w => w.id === id);
      if (index !== -1) {
        writers.splice(index, 1);
        addHistory('writer', 'remove', id);
      }
    }
    updateUI();
  }

  // 切换历史面板
  function toggleHistoryPanel() {
    const historyPanel = document.getElementById('historyPanel');
    const overlay = document.getElementById('overlay');

    historyPanel.classList.toggle('active');
    overlay.classList.toggle('active');
  }

  // 事件绑定
  document.getElementById('addReaderBtn').addEventListener('click', createReader);
  document.getElementById('addWriterBtn').addEventListener('click', createWriter);
  document.getElementById('toggleHistoryBtn').addEventListener('click', toggleHistoryPanel);
  document.getElementById('closeHistoryBtn').addEventListener('click', toggleHistoryPanel);
  document.getElementById('overlay').addEventListener('click', toggleHistoryPanel);

  // 速度控制
  const speedSlider = document.getElementById('speedSlider');
  const speedValue = document.getElementById('speedValue');

  speedSlider.addEventListener('input', function() {
    speedFactor = parseInt(this.value);
    speedValue.textContent = `${speedFactor}x`;
  });

  // 初始化
  updateUI();
</script>
</body>
</html>